package com.pig4cloud.pig.ads.runner;

import com.pig4cloud.pig.ads.service.AdvCreativeService;
import com.pig4cloud.pig.ads.service.AdvCreativeServiceDetailService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class SynAdCreativeWorker implements Runnable {

	private AdvCreativeService advCreativeService;

	private AdvCreativeServiceDetailService advCreativeServiceDetailService;

	private String advertiserId;

	private Long adId;

	//最大重试次数
	private static final Integer tryTimes = 6;
	//重试间隔时间单位秒
	private static final Integer[] intervalTime = {15, 60, 120, 150, 300, 600};

	public SynAdCreativeWorker(AdvCreativeService advCreativeService, AdvCreativeServiceDetailService advCreativeServiceDetailService, String advertiserId, Long adId) {
		this.advCreativeService = advCreativeService;
		this.advCreativeServiceDetailService = advCreativeServiceDetailService;
		this.advertiserId = advertiserId;
		this.adId = adId;
	}


	@Override
	public void run() {
			this.fetchCreative();
	}

	private void fetchCreative(){
		try {
			Integer retryNum = 1;
			while (retryNum <= tryTimes) {
				try {
					// 拉取并保存第三方广告创意列表
					advCreativeService.getAdCreativeByAdId(advertiserId, adId);

					//拉取并保存第三方广告创意详情
					advCreativeServiceDetailService.saveAdCreativeDetailList(advertiserId, adId);

					// 可能头条获取创意不是及时的，可以用延时线程池，不用重试6次，暂时不变
					TimeUnit.SECONDS.sleep(intervalTime[retryNum-1]);
					log.info("计划广告计划{}的创意：第{}次查询...", adId, retryNum);
					retryNum++;
				} catch (Throwable e) {
					retryNum++;
					TimeUnit.SECONDS.sleep(intervalTime[retryNum-1]);
					continue;
				}
			}

		}catch(Throwable e){
			log.error("拉取第三方广告创意失败", e);
		}
	}
}
